package com.freewater.springboot.demo.testmanagedtransaction;

import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

import java.util.List;

public class UserRepository {

    private final SessionFactory sessionFactory;

    public UserRepository(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public User userById(long id) {
        return sessionFactory.getCurrentSession().get(User.class, id);
    }

    public void addUser(User user) {
        this.sessionFactory.getCurrentSession().persist(user);
    }

    public void updateUser(User user) {
        this.sessionFactory.getCurrentSession().merge(user);
    }

    public void remove(User user) {
        this.sessionFactory.getCurrentSession().remove(user);
    }

    public List<User> allUsers() {
        Query<User> fromUser = this.sessionFactory.getCurrentSession()
                .createQuery("from User", User.class);
        return fromUser.list();
    }
}
